<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音频可视化</title>
    <style>
        * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
#container {
    position: absolute;
    top: 0;
    left: 0;
    background: black;
    width: 100%;
    height: 100%;
}
#canvas1 {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: antiquewhite;
}
#audio1 {
    width: 50%;
    margin: 50px auto;
    display: block;
}

    </style>
</head>
<body>
    <canvas id="canvas1"  ></canvas>
    <audio id="audio1" src="./477618.mp3" controls ></audio>
    <script >


const container = document.getElementById('container');
const canvas = document.getElementById('canvas1')
const ctx = canvas.getContext('2d');
const audio1 = document.getElementById('audio1');

// 初始化canvas的尺寸
function initCvs(){
    ctx.width = window.innerWidth*devicePixelRatio;
    ctx.height = (window.innerHeight/2)*devicePixelRatio;
    console.log(ctx.width ,ctx.height)
}
initCvs();
let  isInit = false;
let dataArray,analyser ;
audio1.onplay=function(){
    if(isInit){
        return ;
    }
    // 初始化
    const audioContext = new AudioContext();//创建音频上下文
    const source = audioContext.createMediaElementSource(audio1);//创建音频源节点
    analyser = audioContext.createAnalyser();
    analyser.fftSize = 512;
    // 创建数组，用于接收分析器节点的分析数据
    dataArray = new Uint8Array(analyser.frequencyBinCount);
    source.connect(analyser)
    analyser.connect(audioContext.destination)
    isInit = true;
}

// 把分析的波形绘制到canvas上
function draw(){
    requestAnimationFrame(draw);
    // 清空画布
    const {width,height} =ctx;
    ctx.clearRect(0,0,width,height);
    if(!isInit){
        return
    }
   
    // 让分析器节点分析出数据到数组中
    analyser.getByteFrequencyData(dataArray);
    const len = dataArray.length;
    const barWidth = width /len ;
    ctx.fillStyle = 'white'
    console.log(len)
    for(let i=0;i<len;i++){
        const data = dataArray[i];//<256[数组里面的数据是无符号int,故最大值为256]
        const barHeight = (data/255)*height;
        const x = i * barWidth;
        const y = (height - barHeight);
        // console.log(x,y,barWidth, barHeight)
        ctx.fillRect (x,y,barWidth, barHeight)
    }
}

draw();

// ctx.fillStyle = "rgb(200,0,0)";
//绘制矩形
// ctx.fillRect (0, 40, 55, 50);
// ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
// ctx.fillRect (1393.4375,487.28125,14.21875,153.4);
    </script>
    
</body>
</html>